package com.trace.app.contract;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.trace.app.entity.DTO.RecordDTO;
import com.trace.app.entity.Record;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.StringUtils;
import org.hyperledger.fabric.gateway.Contract;
import org.hyperledger.fabric.gateway.ContractException;
import org.hyperledger.fabric.gateway.Gateway;
import org.hyperledger.fabric.gateway.Network;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @author : lyj
 * @Timer : 2024/4/28
 * @Description :
 */
@Slf4j
@AllArgsConstructor
@Component
public class RecordContractUtil {
    final Gateway gateway;

    private Contract getContract() {
        Network network = gateway.getNetwork("mychannel");
        // 获取合约
        return network.getContract("trace-contract");
    }


    public Record getRecordByKey(String key) throws ContractException {
        Contract contract = getContract();
        byte[] record = contract.evaluateTransaction("queryRecord", key);
        String recordJSON = StringUtils.newStringUtf8(record);
        return JSON.parseObject(recordJSON, Record.class);
    }

    public Record createRecord(Record record) throws ContractException, TimeoutException, InterruptedException {

        Contract contract = getContract();
        byte[] bytes = contract.submitTransaction("createRecord",
                String.valueOf(record.getId()),
                String.valueOf(record.getRawId()),
                String.valueOf(record.getUserId()),
                record.getLocation(),
                record.getRemarks(),
                record.getImg());

        String recordJSON = StringUtils.newStringUtf8(bytes);

        return JSON.parseObject(recordJSON, Record.class);
    }


    public void deleteRecordByKey(@PathVariable String key) throws ContractException, TimeoutException, InterruptedException {
        Contract contract = getContract();
        byte[] cat = contract.submitTransaction("deleteRecord", key);
    }
}
